package com.apotik.legenda.dialog;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import com.apotik.legenda.dao.PurchaseDao;
import com.apotik.legenda.frameinternal.PembelianInternalFrame;
import com.apotik.legenda.model.Purchases;
import com.apotik.legenda.model.Supplier;
import com.apotik.legenda.model.User;
import com.apotik.legenda.observer.GeneralObserver;
import com.apotik.legenda.util.CalendarUtil;

import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.SystemColor;

import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JButton;

public class AddEditPurchaseDialog extends JDialog implements ActionListener {
	private static final long serialVersionUID = 1L;

	private GeneralObserver observer;
	private User user;
	private Purchases currentPurchase;
	private List<Supplier> supplierList;
	private List<String> yearList = new ArrayList<>();
	private List<String> monthList = new ArrayList<>();
	private List<String> dateList = new ArrayList<>();
	private int selectedYearIndex;
	private int selectedMonthIndex;
	private int selectedDayIndex;
	private int activePageIndex = -1;
	
	private JTextField textFieldNoFaktur;
	private JButton btnSubmit;
	private JButton btnCancel;
	
	@SuppressWarnings("rawtypes")
	private JComboBox comboBoxSupplier;
	@SuppressWarnings("rawtypes")
	private JComboBox comboBoxThnBeli;
	@SuppressWarnings("rawtypes")
	private JComboBox comboBoxBlnBeli;
	@SuppressWarnings("rawtypes")
	private JComboBox comboBoxTglBeli;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public AddEditPurchaseDialog(GeneralObserver observer, User user, List<Supplier> supplierList, int activePageIndex, String title) {
		this.observer = observer;
		this.user = user;
		this.supplierList = supplierList;
		this.activePageIndex = activePageIndex;
		
		setTitle(title);
		setSize(500, 200);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		
		JPanel panel = new JPanel();
		panel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new MatteBorder(0, 0, 1, 0, (Color) SystemColor.controlShadow));
		panel.add(panel_1, BorderLayout.NORTH);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new EmptyBorder(3, 3, 3, 3));
		panel_1.add(panel_2, BorderLayout.CENTER);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_3 = new JPanel();
		panel_2.add(panel_3, BorderLayout.NORTH);
		panel_3.setLayout(new GridLayout(0, 2, 0, 3));
		
		JLabel lblSupplier = new JLabel("Supplier");
		panel_3.add(lblSupplier);
		lblSupplier.setFont(new Font("Tahoma", Font.PLAIN, 13));
		
		comboBoxSupplier = new JComboBox();
		panel_3.add(comboBoxSupplier);
		comboBoxSupplier.setFont(new Font("Tahoma", Font.PLAIN, 12));
		comboBoxSupplier.setModel(comboboxModelSuppliers());
		
		JLabel lblNomorFaktur = new JLabel("Nomor Faktur");
		panel_3.add(lblNomorFaktur);
		lblNomorFaktur.setFont(new Font("Tahoma", Font.PLAIN, 13));
		
		textFieldNoFaktur = new JTextField();
		panel_3.add(textFieldNoFaktur);
		textFieldNoFaktur.setFont(new Font("Tahoma", Font.PLAIN, 12));
		textFieldNoFaktur.setColumns(10);
		
		JPanel panel_4 = new JPanel();
		panel_4.setBorder(new EmptyBorder(3, 0, 0, 0));
		panel_2.add(panel_4);
		panel_4.setLayout(new GridLayout(0, 2, 0, 0));
		
		JLabel lblTanggalPembelian = new JLabel("Tanggal Pembelian");
		panel_4.add(lblTanggalPembelian);
		lblTanggalPembelian.setFont(new Font("Tahoma", Font.PLAIN, 13));
		
		JPanel panel_5 = new JPanel();
		panel_4.add(panel_5);
		panel_5.setLayout(new BorderLayout(2, 0));
		
		comboBoxThnBeli = new JComboBox();
		panel_5.add(comboBoxThnBeli, BorderLayout.WEST);
		comboBoxThnBeli.setModel(comboboxModelYear());
		comboBoxThnBeli.setSelectedIndex(selectedYearIndex);
		
		comboBoxBlnBeli = new JComboBox();
		panel_5.add(comboBoxBlnBeli, BorderLayout.CENTER);
		comboBoxBlnBeli.setModel(comboboxModelMonth());
		comboBoxBlnBeli.setSelectedIndex(selectedMonthIndex);
		
		comboBoxTglBeli = new JComboBox();
		panel_5.add(comboBoxTglBeli, BorderLayout.EAST);
		comboBoxTglBeli.setModel(comboboxModelDays());
		comboBoxTglBeli.setSelectedIndex(selectedDayIndex);
		
		JPanel panel_6 = new JPanel();
		panel.add(panel_6, BorderLayout.SOUTH);
		panel_6.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_7 = new JPanel();
		panel_7.setBorder(new EmptyBorder(3, 0, 0, 0));
		panel_6.add(panel_7);
		panel_7.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_8 = new JPanel();
		panel_7.add(panel_8, BorderLayout.EAST);
		
		btnSubmit = new JButton("Submit");
		btnSubmit.addActionListener(this);
		panel_8.add(btnSubmit);
		
		btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(this);
		panel_8.add(btnCancel);
		
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private DefaultComboBoxModel comboboxModelSuppliers(){
		DefaultComboBoxModel model = new DefaultComboBoxModel<>();
		model.addElement(" - Pilih Supplier -");
		
		if(supplierList!=null){
			for(Supplier o: supplierList){
				model.addElement(o.getSupplierName());
			}
		}
		
		return model;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private DefaultComboBoxModel comboboxModelYear(){
		DefaultComboBoxModel model = new DefaultComboBoxModel<>();
		//model.addElement(" - Tahun -");
		
		Calendar cal = CalendarUtil.calendarNow();
		int yearNow = cal.get(Calendar.YEAR);
		
		int startYear = 2013;
		int sizeYear = (yearNow+3)-startYear;
		
		for(int i=0;i<sizeYear;i++){
			int yearInt = startYear+i;
			String yearStr = Integer.toString(yearInt);
			model.addElement(yearStr);
			yearList.add(yearStr);
			
			if(yearInt==yearNow){
				selectedYearIndex = i;
			}
		}
		
		
		
		return model;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private DefaultComboBoxModel comboboxModelMonth(){
		DefaultComboBoxModel model = new DefaultComboBoxModel<>();
		//model.addElement(" - Bulan -");
		
		String jan = "JANUARI";
		String feb = "FEBRUARI";
		String mar = "MARET";
		String apr = "APRIL";
		String mei = "MEI";
		String jun = "JUNI";
		String jul = "JULI";
		String agt = "AGUSTUS";
		String sep = "SEPTEMBER";
		String okt = "OKTOBER";
		String nov = "NOVEMBER";
		String des = "DESEMBER";
		
		model.addElement(jan);
		model.addElement(feb);
		model.addElement(mar);
		model.addElement(apr);
		model.addElement(mei);
		model.addElement(jun);
		model.addElement(jul);
		model.addElement(agt);
		model.addElement(sep);
		model.addElement(okt);
		model.addElement(nov);
		model.addElement(des);
		
		monthList.add(jan);
		monthList.add(feb);
		monthList.add(mar);
		monthList.add(apr);
		monthList.add(mei);
		monthList.add(jun);
		monthList.add(jul);
		monthList.add(agt);
		monthList.add(sep);
		monthList.add(okt);
		monthList.add(nov);
		monthList.add(des);
		
		Calendar cal = CalendarUtil.calendarNow();
		int monthNow = cal.get(Calendar.MONTH);
		selectedMonthIndex = monthNow;
		
		return model;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private DefaultComboBoxModel comboboxModelDays(){
		DefaultComboBoxModel model = new DefaultComboBoxModel<>();
		//model.addElement(" - Tgl -");
		
		Calendar cal = CalendarUtil.calendarNow();
		int dayNow = cal.get(Calendar.DAY_OF_MONTH);
		
		for(int i=1;i<32;i++){
			String s = Integer.toString(i);
			model.addElement(s);
			dateList.add(s);
		}
		
		selectedDayIndex = dayNow-1;
		
		return model;
	}
	
	public void editAction(Purchases p){
		if(p!=null){
			this.currentPurchase = p;
			
			String noFaktur = "";
			if(p.getInvoiceNo()!=null){
				noFaktur = p.getInvoiceNo();
			}
			
			int supplierIndex = 0;
			if(p.getSupplier()!=null && supplierList!=null){
				for(int i=0;i<supplierList.size();i++){
					Supplier o = supplierList.get(i);
					if(o.getSupplierCode().equalsIgnoreCase(p.getSupplier().getSupplierCode())){
						supplierIndex = i+1;
					}
				}
			}
			
			
			int thnIndex = 0;
			int blnIndex = 0;
			int tglIndex = 0;
			if(p.getPurchaseDate()!=null){
				Calendar cal = CalendarUtil.calendarNow();
				cal.setTime(p.getPurchaseDate());
				
				int thn = cal.get(Calendar.YEAR);
				int bln = cal.get(Calendar.MONTH);
				int tgl = cal.get(Calendar.DAY_OF_MONTH);
				
				for(int i=0;i<yearList.size();i++){
					String y = yearList.get(i);
					if(y.equalsIgnoreCase(Integer.toString(thn))){
						thnIndex = i;
					}
				}
				
				blnIndex = bln;
				
				for(int i=0;i<dateList.size();i++){
					String d = dateList.get(i);
					if(d.equalsIgnoreCase(Integer.toString(tgl))){
						tglIndex = i;
					}
				}
			}
			
			textFieldNoFaktur.setText(noFaktur);
			comboBoxSupplier.setSelectedIndex(supplierIndex);
			comboBoxThnBeli.setSelectedIndex(thnIndex);
			comboBoxBlnBeli.setSelectedIndex(blnIndex);
			comboBoxTglBeli.setSelectedIndex(tglIndex);
		}
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		
		if(source==btnSubmit){
			int selectedSupplierIndex = comboBoxSupplier.getSelectedIndex();
			if(selectedSupplierIndex==0){
				JOptionPane.showMessageDialog(null, "Silahkan pilih supplier", "Exception", JOptionPane.ERROR_MESSAGE);
				comboBoxSupplier.requestFocus();
				return;
			}
			Supplier supplier = supplierList.get(selectedSupplierIndex-1);
			
			String noFaktur = textFieldNoFaktur.getText().trim();
			if(noFaktur.isEmpty()){
				JOptionPane.showMessageDialog(null, "Silahkan isi nomor faktur", "Exception", JOptionPane.ERROR_MESSAGE);
				textFieldNoFaktur.requestFocus();
				return;
			}
			
			String thnStr = (String) comboBoxThnBeli.getSelectedItem();
			int blnIndex = comboBoxBlnBeli.getSelectedIndex();
			String tglStr = (String) comboBoxTglBeli.getSelectedItem();
			
			Calendar calBeli = CalendarUtil.calendarNow();
			calBeli.set(Calendar.YEAR, Integer.parseInt(thnStr));
			calBeli.set(Calendar.MONTH, blnIndex);
			calBeli.set(Calendar.DAY_OF_MONTH, Integer.parseInt(tglStr));
			
			Purchases p = null;
			if(currentPurchase!=null){
				p = currentPurchase; 
				p.setUpdatedBy(user);
				p.setUpdatedDate(CalendarUtil.dateNow());
			}else{
				p = new Purchases(); 
				p.setAmountItem(new BigDecimal(0));
				p.setAmountDiscount(new BigDecimal(0));
				p.setAmountPpn(new BigDecimal(0));
				p.setAmountInvoice(new BigDecimal(0));
				p.setCreatedBy(this.user);
				p.setCreatedDate(CalendarUtil.dateNow());
			}
			p.setSupplier(supplier);
			p.setInvoiceNo(noFaktur);
			p.setPurchaseDate(calBeli.getTime());
			
			PurchaseDao dao = new PurchaseDao();
			dao.saveOrUpdate(p);
			
			HashMap<String, Object> hm = new HashMap<>();
			hm.put(PembelianInternalFrame.OBSERBER_FROM, PembelianInternalFrame.OBSERBER_PURCHASE);
			hm.put("activePageIndex", activePageIndex);
			observer.response(hm);
			
			this.setVisible(false);
		}else if(source==btnCancel){
			this.setVisible(false);
		}
		
	}
	
}
